package avicit.bdp.dcs.job.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.dto.api.APIHttpDefinition;
import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.dcs.job.dao.DcsJobDao;
import avicit.bdp.dcs.job.dto.ApiDefinitionDto;
import avicit.bdp.dcs.job.dto.JobDTO;
import avicit.bdp.dcs.precheck.service.PrecheckService;
import avicit.bdp.dcs.task.service.ApiDefinitionService;
import avicit.bdp.dcs.task.service.TaskService;
import avicit.bdp.dcs.tools.enums.SyncMode;
import avicit.platform6.commons.utils.ComUtil;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @金航数码科技有限责任公司
 * @作者：MAYI
 * @邮箱：mayanj@avic-digital.com
 * @创建时间： 2022-02-28 15:10
 * @类说明： API作业服务类
 * @修改记录：
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ApiJobService extends BaseService<DcsJobDao, JobDTO> implements JobInterface {

    private static final Logger logger = LoggerFactory.getLogger(ApiJobService.class);

    private final TaskService taskService;
    private final PrecheckService precheckService;
    private final ApiDefinitionService apiDefinitionService;

    @Autowired
    public ApiJobService(TaskService taskService,
                         PrecheckService precheckService,
                         ApiDefinitionService apiDefinitionService) {

        this.taskService = taskService;
        this.precheckService = precheckService;
        this.apiDefinitionService = apiDefinitionService;
    }

    /**
     * 作业配置第二步(保存表映射关系)
     */
    @Override
    public void saveTableMapping(JobDTO oldJobDTO, JobDTO newJobDTO) throws Exception {
        CheckParaUtils.checkObjectValidity(newJobDTO.getProcessMode(), logger, "已存在表的处理模式必填");
        CheckParaUtils.checkStringValidity(newJobDTO.getSelectedTable(), logger, "接口URL必填");
        APIHttpDefinition apiHttpDefinition = newJobDTO.getApiHttpDefinition();
        CheckParaUtils.checkObjectValidity(apiHttpDefinition, logger, "请填写API定义信息");

        // 1、更新Job信息
        if(apiHttpDefinition.isHaveIncrement()){
            newJobDTO.setSyncMode(SyncMode.DATAX_INCREMENT_SYNC.getCode());
        }else{
            newJobDTO.setSyncMode(SyncMode.TOTAL_SYNC.getCode());
        }
        this.updateByPrimaryKeySelective(newJobDTO);

        // 2、保存或修改api定义
        ApiDefinitionDto queryApiDefinitionDto = new ApiDefinitionDto();
        queryApiDefinitionDto.setJobId(newJobDTO.getId());
        ApiDefinitionDto apiDefinitionDto = apiDefinitionService.selectOne(queryApiDefinitionDto);
        if (apiDefinitionDto != null) {
            APIHttpDefinition oldApiHttpDefinition = JSON.parseObject(apiDefinitionDto.getDefinitionJson(), APIHttpDefinition.class);
            if (oldApiHttpDefinition != null) {
                apiHttpDefinition.setDataMode(oldApiHttpDefinition.getDataMode());
                apiHttpDefinition.setDataRootPath(oldApiHttpDefinition.getDataRootPath());
            }
            ApiDefinitionDto deleteDto = new ApiDefinitionDto();
            deleteDto.setId(apiDefinitionDto.getId());
            apiDefinitionService.delete(deleteDto);
        }
        apiDefinitionDto = new ApiDefinitionDto();
        apiDefinitionDto.setId(ComUtil.getId());
        apiDefinitionDto.setJobId(newJobDTO.getId());
        apiDefinitionDto.setDefinitionJson(JSON.toJSONString(apiHttpDefinition));
        apiDefinitionService.insert(apiDefinitionDto);

        // 2、批量新增或修改任务
        taskService.saveTasksByJob(newJobDTO.getId());

        // 3、新增预检查信息(先删除再新增)
        precheckService.saveJobPrecheck(newJobDTO.getId());
    }
}
